#include "httpServer.hpp"
#include <memory>

using namespace std;
using namespace server;

void Usage(std::string proc)
{
    cerr << "Usage:\n\t" << proc << " port\r\n\r\n";
}

std::string suffixToDesc(const std::string suffix)
{
    std::string ct = "Content-Type: ";
    if (suffix == ".html")
        ct += "text/html";
    else if (suffix == ".jpg")
        ct += "application/x-jpg";
    ct += "\r\n";
    return ct;
}

// 1. 服务器和网页分离，html
// 2. url -> / : web根目录
bool Get(const HttpRequest &req, HttpResponse &resp)
{
    // for test
    cout << "----------------------http start---------------------------" << endl;
    cout << req.inbuffer;
    std::cout << "method: " << req.method << std::endl;
    std::cout << "url: " << req.url << std::endl;
    std::cout << "httpversion: " << req.httpversion << std::endl;
    std::cout << "path: " << req.path << std::endl;
    std::cout << "suffix: " << req.suffix << std::endl;
    std::cout << "size: " << req.size << "字节" << std::endl;
    cout << "----------------------http end---------------------------" << endl;

    // std::string respline = "HTTP/1.1 200 OK\r\n";
    std::string respline = "HTTP/1.1 307 Permanent Redirect\r\n";
    std::string respheader = suffixToDesc(req.suffix);

    respheader += "Location: https://www.qq.com/\r\n";
    std::string respblank = "\r\n";
    // std::string body = "<html lang=\"en\"><head><meta charset=\"UTF-8\"><title>for test</title><h1>hello world</h1></head><body><p>多情只有春庭月，犹为离人照落花</p></body></html>";

    std::string body;
    body.resize(req.size + 1);
    if (!Util::readFile(req.path, (char *)body.c_str(), req.size))
    {
        Util::readFile(html_404, (char *)body.c_str(), req.size);
    }

    respheader += "Content-Length: ";
    respheader += to_string(body.size());
    respheader += "\r\n";

    resp.outbuffer += respline;
    resp.outbuffer += respheader;
    resp.outbuffer += respblank;

    cout << "----------------------http response start---------------------------" << endl;
    std::cout << "resp.outbuffer" << resp.outbuffer << std::endl;
    cout << "----------------------http response end---------------------------" << endl;
    resp.outbuffer += body;

    return true;
}

// ./httpServer port
int main(int argc, char *argv[])
{
    // if(argc != 2)
    // {
    //     Usage(argv[0]);
    //     exit(0);
    // }
    // uint16_t port = atoi(argv[1]);
    // unique_ptr<httpServer> httpsvr(new httpServer(Get, port));

    unique_ptr<httpServer> httpsvr(new httpServer(Get));
    httpsvr->initServer();
    httpsvr->start();

    return 0;
}

